package com.my.study.aop.aspect;

import com.my.study.aop.annotation.FilterType;
import com.my.study.enums.ApiTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;

@Component
@Slf4j
@Aspect
public class FilterTypeAspect {

    @Around("@annotation(filterType)")
    public Object around(ProceedingJoinPoint joinPoint,FilterType filterType) throws Throwable {
        ApiTypeEnum apiTypeEnum = filterType.type();
        Object[] args = joinPoint.getArgs();
        // 获取方法参数
        ServerWebExchange exchange = (ServerWebExchange) args[0];
        GatewayFilterChain chain = (GatewayFilterChain) args[1];
        // 满足执行filter
        String path = exchange.getRequest().getURI().getPath();
        if(getApiTypeEnum(path) == apiTypeEnum){
            return joinPoint.proceed();
        }
        // 不满足转发
        return chain.filter(exchange);
    }

    /**
     * 获取api类型
     *
     * @param path
     * @return
     */
    private ApiTypeEnum getApiTypeEnum(String path){
        if(path.contains(ApiTypeEnum.PUBLIC_API.code)){
            return ApiTypeEnum.PUBLIC_API;
        }else if (path.contains(ApiTypeEnum.INNER_API.code)){
            return ApiTypeEnum.INNER_API;
        }else {
            List<String> strings = Arrays.asList(ApiTypeEnum.LOGIN_LOGOUT_API_REGISTER_API_API.code.split(","));
            for (String api:strings){
                if(path.contains(api)){
                    return ApiTypeEnum.LOGIN_LOGOUT_API_REGISTER_API_API;
                }
            }
            return ApiTypeEnum.NORMAL_API;
        }
    }
}
